package com.flycms.module.role.service;

import com.flycms.module.role.model.AdminRole;
import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author huangzt
 * @version 1.0
 * @date 2020/2/25 14:24
 */
@Setter
@Getter
class TreeNode {
    protected long id;
    protected long parentId;
    protected String name;
    protected String url;
    protected List<TreeNode> children = new ArrayList<>();

    public void add(TreeNode node) {
        children.add(node);
    }


    /**
     * 两层循环实现建树
     *
     * @param treeNodes 传入的树节点列表
     * @return
     */
    public static <T extends TreeNode> List<T> bulid(List<T> treeNodes, Object root) {

        List<T> trees = new ArrayList<>();

        for (T treeNode : treeNodes) {

            if (root.toString().equals(treeNode.getParentId()+"")) {
                trees.add(treeNode);
            }

            for (T it : treeNodes) {
                if (it.getParentId() == treeNode.getId()) {
                    if (treeNode.getChildren() == null) {
                        treeNode.setChildren(new ArrayList<>());
                    }
                    treeNode.add(it);
                }
            }
        }
        return trees;
    }

    /**
     * 使用递归方法建树
     *
     * @param treeNodes
     * @return
     */
    public static <T extends TreeNode> List<T> buildByRecursive(List<T> treeNodes, Object root) {
        List<T> trees = new ArrayList<>();
        for (T treeNode : treeNodes) {
            if (root.equals(treeNode.getParentId())) {
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNodes
     * @return
     */
    public static <T extends TreeNode> T findChildren(T treeNode, List<T> treeNodes) {
        for (T it : treeNodes) {
            if (treeNode.getId() == it.getParentId()) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.add(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }

    public static List<TreeNode> getDeptTree(List<AdminRole> depts) {
        List<TreeNode> treeList = depts.stream()
                .filter(dept -> !dept.getId().equals(dept.getPid()))
                .map(dept -> {
                    TreeNode node = new TreeNode();
                    node.setId(dept.getId());
                    node.setParentId(dept.getPid());
                    node.setName(dept.getRemark());
                    node.setUrl(dept.getUrlKey());
                    return node;
                }).collect(Collectors.toList());
        return bulid(treeList, 0);
    }
}
